#!/usr/bin/env bash
# Copyright (c) 2021 maminjie <canpool@163.com>
# SPDX-License-Identifier: MulanPSL-2.0

method_def yumpkg

usage_yumpkg() {
printf "yumpkg (yump, ypm): Verify rpm packages using yum

usage:
    ${PROG} ypm subcmd [args]

using to install/localinstall/remove/update/downgrade packages

NOTE: the names of packages are obtained from local *.rpm

subcmd:
    install (ins)           Install the packages from yumrepo
    localinstall (lins)     Install the local rpm packages
    update (up)             Update the packages
    downgrade (down)        Downgrade the packages
    remove (rm)             Remove the pacages

args:
    --repo xxx ..
"
}

alias_def yumpkg yump ypm
# do_yumpkg subcmd [args]
do_yumpkg() {
    local subcmd=$1

    if [ $# -gt 0 ]; then
        shift
    fi

    case $subcmd in
        "install"|"ins")
            yumpkg_install "$@"
            ;;
        "localinstall"|"lins")
            yumpkg_localinstall "$@"
            ;;
        "update"|"up")
            yumpkg_update "$@"
            ;;
        "downgrade"|"down")
            yumpkg_downgrade "$@"
            ;;
        "remove"|"rm")
            yumpkg_remove "$@"
            ;;
        *)
            usage_yumpkg
            ;;
    esac
}

yumpkg_get_binnames() {
    local rpms=$(ls *.rpm)
    local pkgs=""
    for r in $rpms; do
        local name=$(rpm -qi $r 2>/dev/null | grep "Name" | head -n1 | awk '{print $3}')
        if [ -z "$pkgs" ]; then
            pkgs=$name
        else
            pkgs="$pkgs $name"
        fi
    done
    echo "$pkgs"
}

yumpkg_install() {
    local pkgs=$(yumpkg_get_binnames)
    if [ -n "$pkgs" ]; then
	    yum install $pkgs $@
    fi
}

yumpkg_localinstall() {
    local pkgs=$(yumpkg_get_binnames)
    if [ -n "$pkgs" ]; then
        echo "yum install $pkgs"
	    yum install *.rpm $@
    fi
}

yumpkg_update() {
    local pkgs=$(yumpkg_get_binnames)
    if [ -n "$pkgs" ]; then
        echo "yum update $pkgs"
        yum update *.rpm $@
    fi
}

yumpkg_downgrade() {
    local pkgs=$(yumpkg_get_binnames)
    if [ -n "$pkgs" ]; then
	    yum downgrade $pkgs $@
    fi
}

yumpkg_remove() {
    local pkgs=$(yumpkg_get_binnames)
    if [ -n "$pkgs" ]; then
	    yum remove $pkgs $@
    fi
}

